'use client'
import { Button } from '@/components/ui/button'
import Image from 'next/image'
import { useState, useEffect } from 'react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog'
import Pagination from '@/components/Pagination'
import { commonService } from '@/services'
import { useTranslation } from 'react-i18next'
import { Textarea } from '@/components/ui/textarea'
import { LanguageSwitcher } from './LanguageSwitcher'
import SolutionIcon from '@/assets/icons/solutions.svg'
import SearchIcon from '@/assets/icons/search.svg'
import StoreIcon from '@/assets/icons/store.svg'

export function Header() {
  const [open, setOpen] = useState(false)
  const [openVideo, setOpenVideo] = useState(false)
  const { t } = useTranslation('common')

  return (
    <header className="flex h-[60px] justify-between items-center px-6 py-3 border-b border-white/10">
      <div className="flex items-center gap-5">
        <a href="#" className="flex items-center gap-2 text-sm text-white">
          <SolutionIcon />
          <span>Solutions </span>
        </a>
        <a href="#" className="flex items-center gap-2 text-sm text-white">
          <SearchIcon />
          <span>Search</span>
        </a>
        <a href="#" className="flex items-center gap-2 text-sm text-white">
          <StoreIcon />
          <span>Store</span>
        </a>
      </div>
      <div className="flex items-center gap-4">
        <Image
          src="/img/vertu-logo.png"
          alt="Vertu"
          className="h-[30px] w-auto"
          width={100}
          height={30}
          priority
        />
        {/* <span className="text-xs text-gray-500">ENGLAND</span> */}
      </div>
      <div className="flex gap-4 items-center">
        <Button
          className="rounded-full"
          variant="secondary"
          size="sm"
          onClick={() => setOpen(true)}
        >
          {t('header.feedback')}
        </Button>
        <Button
          className="rounded-full"
          size="sm"
          onClick={() => setOpenVideo(true)}
        >
          {t('header.tutorial')}
        </Button>
        {/* <LanguageSwitcher /> */}
      </div>
      <FeedbackDialog open={open} onOpenChange={setOpen} />
      <VideoDialog open={openVideo} onOpenChange={setOpenVideo} />
    </header>
  )
}

const FeedbackDialog = ({
  open,
  onOpenChange,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
}) => {
  const [feedback, setFeedback] = useState('')
  const { t } = useTranslation('common')

  const handleSubmit = async () => {
    try {
      await commonService.feedback(feedback)
      setFeedback('')
    } catch (error) {
      // 错误已经在 request.ts 中统一处理
      console.error(error)
    }
    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={() => onOpenChange(false)}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="text-white text-lg">
            {t('feedback.title')}
          </DialogTitle>
        </DialogHeader>

        <div className="pt-5">
          <Textarea
            placeholder={t('feedback.placeholder')}
            value={feedback}
            onChange={(e) => setFeedback(e.target.value)}
            className="resize-none my-scrollbar min-h-32 border-none w-full rounded-md bg-white/5 focus:ring-1"
          />
          <p className="pt-2.5 text-sm text-white">{t('feedback.contact')}</p>
        </div>

        <DialogFooter className="flex sm:justify-center pt-10">
          <Button
            onClick={handleSubmit}
            disabled={!feedback}
            size="lg"
            className="text-white w-3/4 rounded-full"
          >
            {t('feedback.submit')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

/******************** 视频教程组件 ********************/
interface VideoItem {
  id: number
  title: string
  url: string
}

interface VideoDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

const VideoDialog: React.FC<VideoDialogProps> = ({ open, onOpenChange }) => {
  const [videos, setVideos] = useState<VideoItem[]>([])
  const { t } = useTranslation()

  useEffect(() => {
    commonService
      .courseList({
        pageNum: 1,
        pageSize: 20,
        category_sign: 'videoCreation',
      })
      .then((res) => {
        const data = res.data.map((v) => ({
          id: v.id,
          url: v.content,
          title: v.title,
        }))
        setVideos([...data])
      })
  }, [])

  const [currentPage, setCurrentPage] = useState(1)
  const itemsPerPage = 3
  const totalPages = Math.ceil(videos.length / itemsPerPage)
  const currentVideos = videos.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage,
  )

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-5xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="text-xl font-semibold">
            {t('tutorial.title')}
          </DialogTitle>
        </DialogHeader>

        <div className="grid grid-cols-3 gap-6 py-4">
          {currentVideos.map((video) => (
            <div key={video.id} className="flex flex-col gap-2">
              <div className="relative aspect-video bg-black rounded-lg overflow-hidden">
                <video
                  className="w-full h-full object-cover"
                  controls
                  preload="metadata"
                >
                  <source src={video.url} type="video/mp4" />
                  {t('tutorial.browserNotSupported')}
                </video>
              </div>
              <p className="text-center text-sm font-medium">{video.title}</p>
            </div>
          ))}
        </div>

        <div className="flex justify-center mt-4">
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={setCurrentPage}
          />
        </div>
      </DialogContent>
    </Dialog>
  )
}
